package GUI;
 
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;

import logic.Server;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;



public class BackupDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File file;
	private Server server;
	private JLabel lblReplicationDe;
	private JButton btnCancel;
	public BackupDialog(final File file,final Server server) {
		setTitle("Backup");
		this.setFile(file);
		this.setServer(server);
		this.setLocationRelativeTo(getOwner());

		final SpinnerModel sm = new SpinnerNumberModel(1, 1, 100, 1);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{72, 0};
		gridBagLayout.rowHeights = new int[]{56, 0};
		gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
		getContentPane().setLayout(gridBagLayout);

		{

			JPanel panel = new JPanel();
			GridBagConstraints gbc_panel = new GridBagConstraints();
			gbc_panel.gridx = 0;
			gbc_panel.gridy = 0;
			getContentPane().add(panel, gbc_panel);
			panel.setLayout(new GridLayout(2, 6, 10, 10));
			JLabel lblFile = new JLabel("File");
			panel.add(lblFile);
			JLabel lblNewLabel = new JLabel(file.getName());
			panel.add(lblNewLabel);

			JButton btnBackup = new JButton("Backup");
			panel.add(btnBackup);

			btnBackup.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent arg0) {

					(new Thread(){
						public void run(){	
							try {
								server.backupFile(file.getPath(),(int) sm.getValue());
							} catch (IOException | InterruptedException e) {
								JOptionPane.showMessageDialog(GUI.frame,"Error in File Backup", "Error",JOptionPane.ERROR_MESSAGE);
							}
						}
					}).start();

					dispose();				
				}
			});

			{
				lblReplicationDe = new JLabel("Replication Degree");
				panel.add(lblReplicationDe);
			}
			final JSpinner spinner = new JSpinner(sm);
			panel.add(spinner);
			btnCancel = new JButton("Cancel");
			panel.add(btnCancel);


			btnCancel.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					dispose();
				}
			});
		}


	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public Server getServer() {
		return server;
	}
	public void setServer(Server server) {
		this.server = server;
	}
}
